package com.web.webstart.base.util;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;

import java.util.Map;
import java.util.Properties;

/**
 * Created by duandazhi on 2017/1/2.
 * .yml 格式操作  yaml
 * YML spirng 4.3+ 推荐使用yaml格式
 * 支持map; list等多种数据格式
 *
 * YAML工具类 https://yq.aliyun.com/articles/60723
 * 语法:yaml语法规范 https://yq.aliyun.com/articles/44691?spm=5176.100239.blogcont60723.10.RAFlag
 */
public class YamlUtils {
    private static final Logger logger = Logger.getLogger(YamlUtils.class);

    public static Map<String, Object> yaml2Map(String yamlSource) {
        try {
            YamlMapFactoryBean yaml = new YamlMapFactoryBean();
            yaml.setResources(new ClassPathResource(yamlSource));
            return yaml.getObject();
        } catch (Exception e) {
            logger.error("Cannot read yaml", e);
            return null;
        }
    }

    public static Properties yaml2Properties(String yamlSource) {
        try {
            YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
            yaml.setResources(new ClassPathResource(yamlSource));
            return yaml.getObject();
        } catch (Exception e) {
            logger.error("Cannot read yaml", e);
            return null;
        }
    }
}
